using IcsSEMCtrl.Db;
using IcsSEMCtrl.Global.Device;
using IcsSEMCtrl.Service.Logger;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Security.Permissions;
namespace IcsSEMCtrl.Service.Material
{
    [HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
    public class CarrierManager : Manager
    {
        private const string CLASS = "CarrierManager";
        public object Collection_Monitor = new object();
        public Dictionary<string, Carrier> carriers = new Dictionary<string, Carrier>();
        public CarrierManager(string ownerId, string id) : base(ownerId, id)
        {
            this.loadCarriers();
        }
        //从数据库CARRIER表加载所有的CST
        public void loadCarriers()
        {
            this.carriers = Carrier.LoadCarriers();
        }
        protected override int Add(DBConnection theDB)
        {
            return base.Add(theDB);
        }
        protected override void Delete(DBConnection theDB)
        {
            base.Delete(theDB);
        }
        protected override void Load(DBConnection theDB)
        {
            base.Load(theDB);
        }
        protected override int Save(DBConnection theDB)
        {
            int result = base.Save(theDB);
            return result;
        }
        public void DeleteCarrier(string carrierId)
        {
            Carrier carrier = null;
            if (!string.IsNullOrEmpty(carrierId))
            {
                lock (this.Collection_Monitor)
                {
                    if (this.carriers.ContainsKey(carrierId))
                    {
                        carrier = this.carriers[carrierId];
                    }
                    else
                    {
                        foreach (Carrier current in this.carriers.Values)
                        {
                            if (current.CarrierId == carrierId)
                            {
                                carrier = current;
                                break;
                            }
                        }
                    }
                    if (carrier != null)
                    {
                        try
                        {
                            this.carriers.Remove(carrier.CarrierId);
                            LogHelper.loggerInfo($"从系统物料集合中删除物料信息，物料ID为[{carrier.CarrierId}]");
                            carrier.Delete();
                            LogHelper.loggerInfo($"从物料表中删除物料信息，物料ID为[{carrier.CarrierId}]");
                        }
                        catch (Exception ex)
                        {
                            LogHelper.loggerError("在DeleteCarrier方法中，删除物料信息报错;", ex);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 删除所有的CST
        /// </summary>
        public void DeleteAllCarriers()
        {
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                string SqlString = "DELETE FROM CARRIER";
                //删除数据表数据
                dBConnection.ExecuteUpdate(SqlString);
                //清空物料集合数据
                this.carriers.Clear();

                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception ex)
            {
                Console.WriteLine("清除物料表所有数据失败:" + ex.Message);
            }
        }
        public Carrier[] GetCarrierCopyAll()
        {
            Carrier[] array = new Carrier[this.carriers.Count];
            try
            {
                this.carriers.Values.CopyTo(array, 0);
            }
            catch (Exception ex)
            {
            }
            return array;
        }
        public Dictionary<string, Carrier> GetCarrierAll()
        {
            return this.carriers;
        }
        public Carrier GetCarrier(string carrierId)
        {
            Carrier result;
            if (string.IsNullOrEmpty(carrierId))
            {
                result = null;
            }
            else
            {
                Carrier carrier = null;
                lock (this.Collection_Monitor)
                {
                    if (this.carriers.ContainsKey(carrierId))
                    {
                        result = this.carriers[carrierId];
                        return result;
                    }
                    foreach (Carrier current in this.carriers.Values)
                    {
                        if (current.CarrierId == carrierId)
                        {
                            result = current;
                            return result;
                        }
                    }
                }
                result = carrier;
            }
            return result;
        }
        /// <summary>
        /// 判断两个CSTID是否相同用
        /// </summary>
        /// <param name="carrierId"></param>
        /// <returns></returns>
        public Carrier GetCarrierUnsafe(string carrierId)
        {
            Carrier result;
            if (string.IsNullOrEmpty(carrierId))
            {
                result = null;
            }
            else
            {
                Carrier carrier = null;
                try
                {
                    if (this.carriers.ContainsKey(carrierId))
                    {
                        result = this.carriers[carrierId];
                    }
                    else
                    {
                        while (true)
                        {
                            try
                            {
                                foreach (Carrier current in this.carriers.Values)
                                {
                                    if (current.CarrierId == carrierId)
                                    {
                                        result = current;
                                        return result;
                                    }
                                }
                            }
                            catch (InvalidOperationException ex)
                            {
                                LogHelper.loggerError("在GetCarrierUnsafe方法中报错", ex);
                                continue;
                            }
                            break;
                        }
                        result = carrier;
                    }
                }
                catch (Exception)
                {
                    result = carrier;
                }
            }
            return result;
        }

        public Dictionary<string, string> GetKeyTable()
        {
            int num = 3;
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            lock (this.Collection_Monitor)
            {
                foreach (string current in this.carriers.Keys)
                {
                    if (current.Length > num)
                    {
                        try
                        {
                            string text = current.Substring(current.Length - num, num);
                            if (!dictionary.ContainsKey(text))
                            {
                                dictionary.Add(text, text);
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    else
                    {
                        string text = current;
                        if (!dictionary.ContainsKey(text))
                        {
                            dictionary.Add(text, text);
                        }
                    }
                }
            }
            return dictionary;
        }
        public Carrier GetCarrier64(string carrierId64)
        {
            return this.GetCarrier(carrierId64);
        }
        public Carrier GetCarrierByLocation(string elementID)
        {
            Carrier result = null;
            try
            {
                foreach (Carrier current in this.carriers.Values)
                {
                    if (current.CarrierLoc == elementID)
                    {
                        result = current;
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在[GetCarrierByLocation]方法中报错", ex);
            }
            return result;
        }
        public bool isExistCarrerId(string carrierId)
        {
            bool result;
            if (string.IsNullOrEmpty(carrierId))
            {
                result = false;
            }
            else
            {
                if (this.carriers.ContainsKey(carrierId))
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            return result;
        }
        /// <summary>
        /// 通过port口和buffer位置获取CSTID
        /// </summary>
        /// <param name="elementId"></param>
        /// <param name="subLocation"></param>
        /// <returns></returns>
        public string GetCarrierIdByLocation(string elementId)
        {
            string result = "";
            try
            {
                foreach (Carrier current in this.carriers.Values)
                {
                    if (current.CarrierLoc.Equals(elementId))
                    {
                        result = current.CarrierId;
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在[GetCarrierIdByLocation]方法中报错",ex);
            }
            return result;
        }
        public int GetCarrierCount()
        {
            return this.carriers.Count;
        }
        public List<Carrier> GetWaitInCarriers()
        {
            List<Carrier> list = new List<Carrier>();
            foreach (Carrier current in this.carriers.Values)
            {
                if (current.CarrierState == CarrierState.WAITIN)
                {
                    list.Add(current);
                }
            }
            return list;
        }
        public List<string> GetCarriersId()
        {
            List<string> list = new List<string>();
            foreach (Carrier current in this.carriers.Values)
            {
                list.Add(current.CarrierId);
            }
            return list;
        }
    }
}
